package com.leetcode.partition21;

import java.util.HashMap;
import java.util.Map;

/**
 * @author `RKC`
 * @date 2022/1/26 16:24
 */
public class LC2013检测正方形 {

    public static void main(String[] args) {

    }

    private static class DetectSquares {
        //<x, <y, cnt>>
        private Map<Integer, Map<Integer, Integer>> map = new HashMap<>();

        public DetectSquares() { }

        public void add(int[] point) {
            int x = point[0], y = point[1];
            Map<Integer, Integer> item = map.getOrDefault(x, new HashMap<>());
            item.put(y, item.getOrDefault(y, 0) + 1);
            map.put(x, item);
        }

        public int count(int[] point) {
            int a = point[0], b = point[1], ans = 0;
            Map<Integer, Integer> item = map.getOrDefault(a, null);
            if (item == null) return 0;
            for (Map.Entry<Integer, Integer> entry : item.entrySet()) {
                int y = entry.getKey(), cnt1 = entry.getValue();
                //如果这个点和当前点重合，就不可能找到符合条件的正方形，直接跳过
                if (b == y) continue;
                int len = b - y;
                //当前的边长为len，x只可能取 a-len，a+len
                int[] nums = new int[]{a - len, a + len};
                for (int x : nums) {
                    //查找哈希表中是否有需要的x的点
                    Map<Integer, Integer> res = map.getOrDefault(x, null);
                    if (res == null) continue;
                    //再查有没有b和y，正方形用一条边可以确定另一条边
                    int cnt2 = res.getOrDefault(b, 0), cnt3 = res.getOrDefault(y, 0);
                    ans += cnt1 * cnt2 * cnt3;
                }
            }
            return ans;
        }
    }
}
